package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在读取查询字符串的时候有可能是中文，所以要设置读取格式为utf8
        req.setCharacterEncoding("utf8");
        //按照utf8构造请求
        resp.setCharacterEncoding("utf8");
        //1、获取请求中的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)){
            resp.setContentType("text/html");
            resp.getWriter().write("当前用户名或密码为空！");
            return;
        }
        //2、和数据库中的内容进行比较
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null || !user.getPassword().equals(password)){
            //用户没有查到或者密码不匹配
            resp.setContentType("text/html");
            resp.getWriter().write("用户名或密码错误！");
            return;
        }
        //都正确，创建会话
        HttpSession session = req.getSession(true);
        //把用户信息存储到会话中
        session.setAttribute("user", user);
        //4、返回重定向报文，跳转页面
        resp.sendRedirect("blog_list.html");
    }

    //用于让前端检测当前登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if (session == null){
            //检查会话是否存在，不存在就说明未登录！
            User user = new User();
            //这里的user如果没赋值，会有默认值
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User)session.getAttribute("user");
        if (user == null){
            //虽然有对象，但是会话里没有user对象
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        //已经登录
        //但这里不要返回密码
        user.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
